from PyPDF4 import PdfFileReader, PdfFileWriter,PdfFileMerger
import os

def pdf_delempty(pdf_file_path,path_output):
    reader = PdfFileReader(open(pdf_file_path, 'rb'))
    writer = PdfFileWriter()
    pages = reader.getNumPages()
    for i in range(pages):
        page = reader.getPage(i)
        try:
            text = page.extractText()
        except:
            text = 0
        if text:
            writer.addPage(page)
    writer.write(open(path_output, 'wb'))


def pdf_delempty2(pdf_file_path, path_output):
    time_from = pdf_file_path
    tf = (os.path.getatime(time_from), os.path.getmtime(time_from))
    reader = PdfFileReader(open(pdf_file_path, 'rb'))
    writer = PdfFileWriter()
    pages = reader.getNumPages()
    for i in range(pages):
        page = reader.getPage(i)
        try:
            text = page.extractText()
        except:
            text = 0
        if text:
            writer.addPage(page)
    writer.write(open(path_output, 'wb'))
    time_to = path_output
    os.utime(time_to, tf)

def get_pages(pdf_file_path):
    reader = PdfFileReader(open(pdf_file_path, 'rb'))
    writer = PdfFileWriter()
    pages = reader.getNumPages()
    return pages

def removepages(pdf_file_path, path_output, pat_rem):
    if len(pat_rem) == 0 :
        return True
    l1 = pat_rem.split(" ")
    time_from = pdf_file_path
    tf = (os.path.getatime(time_from), os.path.getmtime(time_from))
    reader = PdfFileReader(open(pdf_file_path, 'rb'))
    writer = PdfFileWriter()
    pages = reader.getNumPages()
    for i in range(pages):
        page = reader.getPage(i)
        if not(str(i+1) in l1):
            writer.addPage(page)
    writer.write(open(path_output, 'wb'))
    time_to = path_output
    os.utime(time_to, tf)





#print( get_pages(r"Z:\31_PTS\01_Projects\ASY\CN.305851.GWM E-Drive_Rotor & Final Assembly\04_Documentation\Email\SINGLE_PAGE\D.05851.545.ST.00_v03.pdf") )
str1 =input("需要删除的页")
removepages(r"Z:\31_PTS\01_Projects\ASY\CN.305851.GWM E-Drive_Rotor & Final Assembly\04_Documentation\Email\SINGLE_PAGE\D.05851.544.ST.00_v07.pdf" ,r"Z:\31_PTS\01_Projects\ASY\CN.305851.GWM E-Drive_Rotor & Final Assembly\04_Documentation\Email\SINGLE_PAGE\D.05851.544.ST.00_v0722.pdf" ,str1)

#pdf_delempty2("D:\\我.pdf","D:\\我_OK.pdf")
#pdf_delempty(r"Z:\31_PTS\01_Projects\TES\CN.505885_XuanFu_6HT-1test\04_Documentation\Email\fast_pdf\D.05587.342.ST.00_1.dwg.pdf", "D:\\我_OK.pdf" )

